<template>
    <div class="arLayout">
        <div class="Box" v-loading="loading" element-loading-text="loading..." element-loading-background="white">
            <p>
                <span>客房类型</span>
                <el-select v-model="info.name_id" class="m-2" placeholder="Select" size="large">
                    <el-option v-for="item in kinds" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </p>
            <p>
                <span>价格</span>
                <el-input-number v-model="info.price" :precision="2" :step="10" :max="10000" />
            </p>
            <p class="upload">
                <span>客房图片</span>
                <span>
                    <upload-box url="/api/room/uploadRoomImage" 
                                :getImgUrl="'/room/getImageUrl?id=' + props.roomId"
                                imgPrefix="/api/room/getImage/"
                                ref="uploadBoxRef"
                                :limit="5" 
                                :autoUpload="true"
                                :id="props.roomId"
                                :data="{ id: props.roomId }"
                                @delImg="delImg"
                    ></upload-box>
                </span> 
            </p>
            <div class="roomSetting">
                <span>房间设施</span>
                <div class="setingBox">
                    <div v-for="item in settingType" :key="item.id">
                        <p>{{ item.name }}</p>
                        <el-checkbox-group v-model="info.devicelist">
                            <el-checkbox v-for="itemm in item.deList" :key="itemm.id" :label="itemm.name"/>
                        </el-checkbox-group>
                    </div>
                </div>
            </div>
            <p class="desc">
                <span>客房描述</span>
                <span>
                    <el-input
                        v-model="info.description"
                        :rows="3"
                        type="textarea"
                        placeholder="房间描述词"
                    />
                </span>
            </p>
            <p>
                <span>添加数量</span>
                <el-input-number v-model="info.num" :step="1" :min="1" :max="100" disabled/>
            </p>
            <div class="childRoom">
                <span>房间状态</span>
                <p>
                    <span v-for="item in info.roomslist" :key="item.id" @click="changeChildInfo(item)">
                        <img  src="../../assets/image/roomOpen.png" v-if="item.state"/>
                        <img  src="../../assets/image/roomClose.png" v-else/>
                        <span>房间{{ item.name }}</span>
                    </span>

                    <span class="last" @click="addRoomItem">
                        <el-icon><Plus /></el-icon>
                    </span>
                </p>
            </div>
            <p class="btn">
                <button @click="changeInfo" :disabled="!isAdd">更新</button>
            </p>
        </div>
    </div> 
    
    <el-dialog v-model="isAddChild" title="创建房间">
        <el-form :inline="true" :model="form" class="formBox demo-dynamic" ref="formRef">
            <el-form-item label="房间号"  prop="name"
            :rules="[
                        {
                            required: true,
                            message: '请输入房间号',
                            trigger: 'blur',
                        },
                        {
                            type: 'number',
                            message: '请输入代号，不要输入字符',
                            trigger: ['blur', 'change'],
                        }
                    ]"

            >
                <el-input v-model.number="form.name" placeholder="请不要重复" clearable />
            </el-form-item>
            <el-form-item label="房间描述"  prop="desc">
                <el-input v-model="form.desc" placeholder="描述" clearable />
            </el-form-item>
            <el-form-item label="房间状态">
                <el-switch
                    v-model="form.state"
                    class="ml-2"
                    inline-prompt
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;"
                    size="large"
                    active-text="开放"
                    inactive-text="维护"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit(formRef)">立即添加</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog v-model="isChangeChild" title="房间操作">
        <el-form :inline="true" :model="roomChildInfo" class="formBox demo-dynamic" ref="formRef">
            <el-form-item label="房间号"  prop="name"
            :rules="[
                        {
                            required: true,
                            message: '请输入房间号',
                            trigger: 'blur',
                        },
                    ]"

            >
                <el-input v-model.number="roomChildInfo.name" placeholder="请不要重复" clearable />
            </el-form-item>
            <el-form-item label="房间描述"  prop="desc">
                <el-input v-model="roomChildInfo.description" placeholder="描述" clearable />
            </el-form-item>
            <el-form-item label="房间状态">
                <el-switch
                    v-model="roomChildInfo.state"
                    class="ml-2"
                    inline-prompt
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;"
                    size="large"
                    active-text="开放"
                    inactive-text="维护"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="updateRoomChild">立即更新</el-button>
                <el-button type="danger" @click="deleteRoom">删除此房间</el-button>
            </el-form-item>
        </el-form>
  </el-dialog>
</template>
    
<script lang="ts" setup>
import { ref, onBeforeMount, computed, reactive } from 'vue'
import { get, post } from '@/http/axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { uploadBox } from '@/components'
import { useRouter } from 'vue-router'
import type { FormInstance } from 'element-plus'

interface Props{
    roomId: string
    hotel_id: string
}
type kindType ={
    id:number
    name:string
}
type infoType = {
    description:string //描述
    devicelist:Array<string>    //子房间列表
    name_id:number
    num:number
    price:number
    roomslist:Array<{
        id:number
        state:boolean
        name:string
    }>
}
type setTypeType = {
    id:number
    name:string
    code:string
    deList:Array<{
        id:number
        name:string
    }>
}
let kinds = ref<Array<kindType>>()
const props = defineProps<Props>()
const router = useRouter()
let isAddChild = ref<boolean>(false)
let isChangeChild = ref<boolean>(false)
let settingType = ref<Array<setTypeType>>([])
let upLoading = ref<boolean>(true)
const formRef = ref<FormInstance>()
const uploadBoxRef = ref()
let setting = ref<any>()
let loading = ref<boolean>(true)
const form = reactive({
    name:'',
    state:true,
    desc:''
})
let info = ref<infoType>({
    description:'', //描述
    devicelist:[],
    name_id:1,
    num:0,
    price:0,
    roomslist:[]
})
let roomChildInfo = reactive({
    description:'',
    id:0,
    name:'',
    state:false
})
onBeforeMount(() => {
    if (!props.roomId) {
        ElMessage.warning('当前无信息，将跳转至客房信息界面')
        let timer = setTimeout(() => {
            clearTimeout(timer)
            router.push({ path: '/main/room/roomInfo' })
        },1000)
        return
    }
    getRoomKinds()
    getRoomType()
    initDate()
})
function getRoomKinds(){
    get('/roomName/queryAll').then(res => {
        kinds.value = res.result
        let timer = setTimeout(() => {
            clearTimeout(timer)
            loading.value = false
        })
    })
}
function delImg(name:string){
    if (uploadBoxRef.value.fileList.length <= 3) {
        ElMessage.error('图片不能少于3张，请添加后再删除')
        upLoading.value = false
        let timer = setTimeout(() => {
            clearTimeout(timer)
            upLoading.value = true
        })
        return
    }
    get('/room/deleteImage?id=' + props.roomId + '&imageId=' + name)
    .then(res => {
        if (res.result) ElMessage.success('删除成功')
        let timer = setTimeout(() => {
            clearTimeout(timer)
            upLoading.value = true
        })
    })
}
function getRoomType() {
    get('/deviceFa/queryAll').then(res => {
        const obj = {}
        settingType.value = res.result
        if (res.result.length) {
            res.result.forEach(el => {
                obj[el.code] = { id: el.id, list: [] }
            })
        }
        setting.value = obj      
    })
}
function initDate() {
    get('/room/queryRoom?id=' + props.roomId).then(res => {
        console.log('房间信息',res);
        Object.keys(info.value).forEach(el => {
            info.value[el] = res.result.room[el]
        })
        info.value['devicelist'] = res.result.devicelist
        info.value['roomslist'] = res.result.roomslist
    }).catch(res => {
        ElMessage.error('房间信息加载失败')
    })
}
function changeInfo() {
    let idList = check()
    if (!idList) {
        return
    }
    post('/room/updateRoom',{
        id: props.roomId,
        name_id: info.value.name_id,
        price: info.value.price,
        description: info.value.description,
        room_device: idList.toString()
    }).then(res => {
        ElMessage.success('更新成功')
        let timer = setTimeout(() => {
            clearTimeout(timer)
            router.push({ path:'/main/room/roomInfo' })
        },1000)
    }).catch(err => {
        ElMessage.error('更新失败')
    })
}
//数据校验是否合格
function check(){
    let idList = [] as Array<any>
    settingType.value.forEach(el => {
        el.deList.forEach(ele => {    
            let item = info.value.devicelist.find(e => e === ele.name)
            if (item) idList.push(ele.id)
        })
    })
    console.log('完成之后',idList);
    
    if (uploadBoxRef.value.fileList.length < 3) {
        ElMessage.error('最少提交3张图片')
        return null
    }
    if (idList.length < 5) {
        ElMessage.error('房间设施最少选择5项')
        return
    }
    return idList
}
//修改子房间
function changeChildInfo(obj:{ description:string, id:number, name:string, state:boolean }){
    roomChildInfo = obj
    isChangeChild.value = true
}
function deleteRoom(){
    ElMessageBox.confirm(
    '您确定删除这条数据吗？','提醒',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
      draggable: true,
    }).then(() => {
        get('/roomS/deleteById?id=' + roomChildInfo.id).then(res => {
            ElMessage.success('删除成功')
            initDate()
            isChangeChild.value = false
        }).catch(err => {
            ElMessage.error('删除失败' + err)
        })
    }).catch(() => {
      ElMessage.warning('删除取消')
    })
}
function updateRoomChild() {
    post('/roomS/updateRoomS',{
        id: roomChildInfo.id,
        room_name: roomChildInfo.name,
        room_state: roomChildInfo.state?'open':'close',
        description: roomChildInfo.description
    }).then(res => {
        ElMessage.success('更新成功')
        initDate()
        isChangeChild.value = false
    }).catch(err => {
        ElMessage.error('更新失败' + err)
    })
}
//添加子房间
function addRoomItem(){
    isAddChild.value = true
}
function onSubmit(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            let flag = true
            info.value.roomslist.forEach(el => {
                if (el.name == form.name) flag = false
            })
            if (!flag) {
                ElMessage.error('房间名冲突，请重新输入')
                form.name = ''
                return false
            }
            post('/roomS/addRoomS',{
                room_id: props.roomId,
                rooms_name: form.name,
                description: form.desc,
                room_state: form.state?'open':'close'
            }).then(res => {
                ElMessage.success('添加成功')
                isAddChild.value = false
                initDate()
            }).catch(err => {
                ElMessage.error('添加失败' + err)
            })
        } else {
            ElMessage.error('表单验证失败，添加失败，请检查')
            return false
        }
    })

}
const isAdd = computed(() => {
    let flag = true
    Object.keys(info.value).forEach(el => {
        if (!info.value[el]){
            flag = false
        }
    })
    return flag
})
</script>
    
<style lang="scss" scoped>
@media  screen and (min-width: 0) and (max-width: 1400px){
    .Box{
        width: 85%;
    }
}
@media  screen and (min-width: 1400px) and (max-width: 1600px){
    .Box{
        width: 80%;
    }
}
@media  screen and (min-width: 1600px) and (max-width: 100vw){
    .Box{
        width: 60%;
    }
}
.arLayout{
    width: 100%;
    @include flexColumnCenter;
    gap: 2px;
    @include allBack;
}
.Box{
    padding: 20px;
    gap: 20px 0;
    box-sizing: border-box;
    background: white;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    justify-content: start;
    align-items: start;
    box-shadow: var(--el-box-shadow);
    & p{
        width: 100%;
        display: flex;
        justify-content: start;
        align-items: center;
        gap: 10px;
        white-space: nowrap;
    }
    & p span:nth-child(1){
        width: 130px;
        background: rgb(52, 152, 219,0.2);
        padding: 6px 0;
        box-sizing: border-box;
        border-radius: 8px;
        @include flexRowCenter;
        user-select: none;
    }
}
.upload{
    & span:nth-child(2){
        border: 1px solid var(--el-border-color);
        width: calc(100% - 140px);
        padding: 10px;
        box-sizing: border-box;
        border-radius: 4px;
        display: flex;
        justify-content: start;
        align-items: start;
        flex-wrap: wrap;
    }
}
.desc{
    & span:nth-child(2){
        width: calc(100% - 140px);
        display: flex;
        justify-content: start;
        align-items: start;
        flex-wrap: wrap;
        box-sizing: border-box;
    }
}
.roomSetting{
    width: 100%;
    display: flex;
    justify-content: start;
    align-items: center;
    gap: 10px;
    white-space: nowrap;
    & span:nth-child(1){
        width: 130px;
        background: rgb(52, 152, 219,0.2);
        padding: 6px 0;
        box-sizing: border-box;
        border-radius: 8px;
        @include flexRowCenter;
        user-select: none;
    }
}
.setingBox{
    width: calc(100% - 140px);
    display: flex;
    justify-content: start;
    align-items: start;
    flex-wrap: wrap;
    gap: 15px;
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
    padding: 10px;
    box-sizing: border-box;
    & div{
        width: 100%;
        display: flex;
        align-content: center;
        justify-content: start;
        flex-wrap: wrap;
        gap: 15px;
        font-size: 13px;
    }
    & div p:nth-child(1){

        padding-bottom: 10px;
        border-bottom: 1px solid var(--el-border-color);
    }
}
.btn{
    justify-content: center !important;
    & button{
        width: 200px;
        border: none;
        background: #3498db;
        color: white;
        outline: none;
    }
    & button:hover{
        background: #2980b9;
    }
    & button:disabled{
        background: #dad9d9;
    }
}
.childRoom{
    width: 100%;
    display: flex;
    justify-content: start;
    align-items: center;
    gap: 10px;
    white-space: nowrap;
    & span:nth-child(1){
        width: 130px;
        background: rgb(52, 152, 219,0.2);
        padding: 6px 0;
        box-sizing: border-box;
        border-radius: 8px;
        @include flexRowCenter;
        user-select: none;
    }
    & p:nth-child(2){
        width: calc(100% - 140px);
        display: flex;
        justify-content: start;
        align-items: center;
        flex-wrap: wrap;
        padding: 10px;
        border: 1px solid var(--el-border-color);
        box-sizing: border-box;
        border-radius: 4px;
        gap:10px;
    }
    & p:nth-child(2) span{
        background: transparent;
        @include flexColumnCenter;
        width: calc((100% - 140px) / 15 );
    }
    & p:nth-child(2) span img:nth-child(1){
        width: 100%;
        height: 100%;
        cursor: pointer;
    }
    & p:nth-child(2) span span:nth-child(2){
        font-size: 12px;
    }
}
.last{
    width: calc((100% - 140px) / 15 );
    aspect-ratio:1;
    border-radius: 4px;
    border: 1px dashed var(--el-border-color);
    cursor: pointer;
    &:hover{
        border: 1px dashed #3498db;
        color: #3498db;
    }
}
.formBox{
    display: flex;
    flex-direction: column;
    justify-content: center;
}
:deep(.el-checkbox){
    width: calc((100% - 105px) / 7);
}
</style>